import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { generatePermissionsByRoles } from '@/utils/permission'

// 获取当前选择的角色
const getCurrentRole = () => {
  try {
    return localStorage.getItem('currentTestRole') || 'admin'
  } catch (error) {
    return 'admin'
  }
}

// 设置当前选择的角色
const setCurrentRole = (role) => {
  try {
    localStorage.setItem('currentTestRole', role)
  } catch (error) {
    console.warn('无法保存角色到localStorage:', error)
  }
}

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  permissions: [],
  canChangePassword: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_CAN_CHANGE_PASSWORD: (state, canChangePassword) => {
    state.canChangePassword = canChangePassword
  }
}

const getters = {
  /**
   * 检查用户是否有指定权限
   */
  hasPermission: (state) => (permission) => {
    const roles = Array.isArray(state.roles) ? state.roles : []
    const permissions = Array.isArray(state.permissions) ? state.permissions : []
    
    if (roles.includes('admin') || permissions.includes('*')) {
      return true
    }
    
    return permissions.includes(permission)
  }
}

const actions = {
  /**
   * 用户登录
   */
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve) => {
      const token = 'admin-token'
      commit('SET_TOKEN', token)
      setToken(token)
      
      dispatch('getInfo').then(() => {
        resolve()
      })
    })
  },

  /**
   * 获取用户信息
   */
  getInfo({ commit, state }) {
    return new Promise((resolve) => {
      const currentRole = getCurrentRole()
      
      // 根据当前角色返回对应的用户信息
      let userData
      
      switch (currentRole) {
        case 'admin':
          userData = {
            roles: ['admin'],
            name: '超级管理员',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            canChangePassword: true
          }
          break
        case 'manager':
          userData = {
            roles: ['manager'],
            name: '普通管理员',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            canChangePassword: true
          }
          break
        case 'user':
          userData = {
            roles: ['user'],
            name: '普通用户',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            canChangePassword: false
          }
          break
        case 'guest':
          userData = {
            roles: ['guest'],
            name: '访客用户',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            canChangePassword: false
          }
          break
        default:
          userData = {
        roles: ['admin'],
            name: '超级管理员',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        canChangePassword: true
          }
      }
      
      const permissions = generatePermissionsByRoles(userData.roles)
      
      const { roles, name, avatar, canChangePassword } = userData
      
      commit('SET_ROLES', roles)
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_PERMISSIONS', permissions)
      commit('SET_CAN_CHANGE_PASSWORD', canChangePassword)
      
      resolve(userData)
    })
  },

  /**
   * 用户登出
   */
  logout({ commit, state, dispatch }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      commit('SET_CAN_CHANGE_PASSWORD', false)
      removeToken()
      resetRouter()
      
      dispatch('tagsView/delAllViews', null, { root: true })
      
      resolve()
    })
  },

  /**
   * 重置token
   */
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      commit('SET_CAN_CHANGE_PASSWORD', false)
      removeToken()
      resolve()
    })
  },
  
  /**
   * 更新用户信息
   */
  updateUserInfo({ commit }, userInfo) {
    const { name, avatar } = userInfo
    return new Promise(resolve => {
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      resolve()
    })
  },
  
  /**
   * 更新用户角色和权限
   */
  updateUserRoles({ commit }, roles) {
    return new Promise(resolve => {
      // 保存当前角色到localStorage
      if (roles && roles.length > 0) {
        setCurrentRole(roles[0])
      }
      
      commit('SET_ROLES', roles)
      
      const permissions = generatePermissionsByRoles(roles)
      commit('SET_PERMISSIONS', permissions)
      
      resolve({ roles, permissions })
    })
  },
  
  /**
   * 更新密码修改权限
   */
  updatePasswordPermission({ commit }, canChangePassword) {
    return new Promise(resolve => {
      commit('SET_CAN_CHANGE_PASSWORD', canChangePassword)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 